package com.whcoding.more.database.config;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;

import javax.sql.DataSource;

/**
 * @className DataSourceConfig
 * @Description  Middle-mybatis配置
 * @Author whcoding
 * @Created Date 2022-11-22 9:46
 * @Modifier
 * @Modified Date
 * @Modified Remark
 * @Version 1.0
 */
@Configuration
@MapperScan(basePackages = {"com.whcoding.more.database.dao.mapper.middle"}, sqlSessionTemplateRef = "middleMybatisSqlSessionTemplate")
public class MiddleMybatisConfig {

    @Bean(name = "middleMybatisSqlSessionFactory")
    public SqlSessionFactory testSqlSessionFactory(@Qualifier("middleMybatisDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver = new PathMatchingResourcePatternResolver();
        String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + "/mapper/middle/**/*.xml";
        bean.setMapperLocations(pathMatchingResourcePatternResolver.getResources(packageSearchPath));
        return bean.getObject();
    }

    @Bean(name = "middleMybatisSqlSessionTemplate")
    public SqlSessionTemplate testSqlSessionTemplate(@Qualifier("middleMybatisSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }


}
